<template>
  <component
    :is="column?.render ?? `el-${column?.el}`"
    v-bind="{ ...handleFormProps, ...placeholder, formParam: _formParam, clearable: true }"
    v-model.trim="_formParam[column?.key ?? handleProp(column.key!)]"
    :data="column?.el === 'tree-select' ? columnEnum : []"
    :options="['cascader', 'select-v2'].includes(column?.el!) ? columnEnum : []"
    :readonly="readonly"
    :disabled="disabled"
  >
    <template v-if="column?.el === 'cascader'" #default="{ data }">
      <span>{{ data[fieldNames.label] }}</span>
    </template>
    <template v-if="column?.el === 'select'">
      <component
        :is="`el-option`"
        v-for="(col, index) in columnEnum"
        :key="index"
        :label="col[fieldNames.label]"
        :value="col[fieldNames.value]"
      ></component>
    </template>
    <slot v-else></slot>
  </component>
</template>

<script setup lang="ts" name="ProFormItem">
import { computed, onMounted, ref } from "vue";
import { handleProp } from "@/utils";
import { ColumnProps } from "@/components/ProForm/interface";
import { arrayToTree } from "@/utils";

interface ProFormItem {
  column: ColumnProps;
  row: { [key: string]: any };
  readonly: boolean;
  multiple: boolean;
}
const props = defineProps<ProFormItem>();

const _enumData = ref([]);

const _formParam = computed(() => props.row);

// 判断 fieldNames 设置 label && value && children 的 key 值
const fieldNames = computed(() => {
  return {
    label: props.column.fieldNames?.label ?? "label",
    value: props.column.fieldNames?.value ?? "value",
    children: props.column.fieldNames?.children ?? "children"
  };
});

// 接收 enumMap (el 为 select-v2 需单独处理 enumData)
const columnEnum = computed(() => {
  let enumData: any = _enumData.value;
  if (props.column?.el === "select-v2" && props.column.fieldNames) {
    enumData = enumData.map((item: { [key: string]: any }) => {
      return { ...item, label: item[fieldNames.value.label], value: item[fieldNames.value.value] };
    });
  }
  return enumData;
});

const getEnumData = async (column: ColumnProps) => {
  let enumData: any = column.enum;
  if (!enumData) return [];

  // 当前 enum 为静态数据，则直接存储到 enumMap
  if (typeof enumData !== "function") return enumData;

  // 当前 enum 为后台数据需要请求数据，则调用该请求接口，并存储到 enumMap
  const { data } = await enumData();

  //处理级联选择控件数据为树形
  const formEl = props.column?.el as string;
  if (formEl.startsWith("tree") || formEl.startsWith("cascader")) {
    const dataTree = arrayToTree(data, "id", "pid", "0");
    return dataTree;
  }

  return data;
};

onMounted(async () => {
  const data = await getEnumData(props.column);
  _enumData.value = data;
});

// 处理透传的 searchProps (el 为 tree-select、cascader 的时候需要给下默认 label && value && children)
const handleFormProps = computed(() => {
  const label = fieldNames.value.label;
  const value = fieldNames.value.value;
  const children = fieldNames.value.children;
  const formEl = props.column?.el;
  let formProps = props.column?.props ?? {};
  if (formEl === "tree-select") {
    formProps = {
      ...formProps,
      props: { ...formProps.props, label, children },
      showCheckbox: props.multiple,
      defaultExpandAll: true,
      multiple: props.multiple,
      checkStrictly: true,
      nodeKey: value,
      valueKey: value
    };
  } else if (formEl === "cascader") {
    formProps = {
      ...formProps,
      props: { ...formProps.props, label, value, children, multiple: props.multiple, checkStrictly: true }
    };
  } else if (formEl === "switch") {
    formProps = { ...formProps.props, activeValue: "1", inactiveValue: "0" };
  } else if (formEl?.startsWith("select")) {
    formProps = { ...formProps.props, multiple: props.multiple };
  }

  return formProps;
});

// 处理默认 placeholder
const placeholder = computed(() => {
  const column = props.column;
  if (["datetimerange", "daterange", "monthrange"].includes(column?.props?.type) || column?.props?.isRange) {
    return {
      rangeSeparator: column?.props?.rangeSeparator ?? "至",
      startPlaceholder: column?.props?.startPlaceholder ?? "开始时间",
      endPlaceholder: column?.props?.endPlaceholder ?? "结束时间"
    };
  }
  const placeholder = column?.props?.placeholder ?? (column?.el?.includes("input") ? "请输入" : "请选择");
  return { placeholder };
});

// 处理默认 disabled
const disabled = computed(() => {
  const formEl = props.column?.el as string;
  if (formEl.startsWith("select") || formEl.startsWith("tree") || formEl.startsWith("cascader")) {
    return props.readonly;
  }
  return false;
});
</script>
